package com.qixin.web.controller.Scan;

import com.alibaba.druid.stat.TableStat;
import com.alibaba.fastjson.JSONObject;
import com.qixin.api.bean.*;
import com.qixin.api.service.*;
import com.qixin.util.cache.EhcacheUtil;
import com.qixin.util.chargeInterfce.Charge.Test;
import com.qixin.util.chargeInterfce.Charge.bean.ChargeDetails;
import com.qixin.util.chargeInterfce.Charge.bean.StopChargeBean;
import com.qixin.util.chargeInterfce.QiXinPublic.StarInterFce;
import com.qixin.util.http.SendHttp;
import com.qixin.util.string.StringCreateUtil;
import com.qixin.util.weixin.CheckUtil;
import com.qixin.util.weixin.WxpubOAuth;
import com.qixin.util.weixin.bean.OAuthResult;
import com.qixin.web.util.ScanUtil;
import com.qixin.web.util.SessionUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Zhang on 2018/10/26.
 * 扫一扫
 */
@Controller
@RequestMapping("/scan")
public class ScanController {
    @Autowired
    ComChargeInfoService comChargeInfoServicel;
    @Autowired
    ComPtUserService comPtUserService;
    @Autowired
    ComPeopleService comPeopleService;
    @Autowired
    ComCarService comCarService;
    @Autowired
    ComCarChargeService comCarChargeService;

    @RequestMapping("/main.html")
    public String main(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws UnsupportedEncodingException {
        //获取回调后 微信发送的code
        String code = request.getParameter("code");
        WxpubOAuth wxpubOAuth = new WxpubOAuth();
        //根据code 等信息 取得openid 和 accesstoken
        OAuthResult oAuthResult = WxpubOAuth.getOpenId(WxpubOAuth.APPID, WxpubOAuth.appSecret, code);
        //openid存进页面
        model.addAttribute("openId", oAuthResult.getOpenid());
        return "/Map/Scan";
    }

    @RequestMapping("/getJSSDK")
    @ResponseBody
    public String getJSSDK(HttpServletRequest request, String url) throws UnsupportedEncodingException {
        Map map = new HashMap<>();
        map = CheckUtil.jsApiSign(url);
        return JSONObject.toJSONString(map);
    }

    //检测充电设备
    @RequestMapping("/checkCharge")
    @ResponseBody
    public Map checkCharge(String param) {
        String checkID = Test.LOCAL_OPERATORID + StringCreateUtil.getRandomNumString(18);
        //转换枪口ID
        String connId = ScanUtil.getConnId(param);
        StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        //检测结果
        String useReslut = starInterFce.checkCharge(token, checkID, connId);
        Map map1 = JSONObject.parseObject(useReslut, Map.class);
        return map1;

    }

    //点击消息通知跳转详情   order订单 由跳转页面请求携带
    @RequestMapping("/info.html")
    public String info(String order, String carPlant, Model model) {
        StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        //启动结果
        String useReslut = starInterFce.findUseCharge(token, order);
        Map map1 = JSONObject.parseObject(useReslut, Map.class);
        model.addAttribute("info", map1);
        model.addAttribute("carPlant", carPlant);
        return "Map/OrderInfo";
    }

    /**
     * 检查车辆余额是否充足
     *
     * @param carBland
     * @return
     */
    @RequestMapping("/checkMoeny")
    @ResponseBody
    public Map checkMoeny(String carBland, HttpSession session) {
        Map resultMap = new HashMap<>();
        //根据登陆的 企业用户 或者 个人用户 查询是否关联了车辆 或者 车辆的金额是否充足
        List<ComCarCharge> comCars;
        if (SessionUtil.getUserFlag(session) == 1) {
            Map flagMap = new HashMap<>();
            flagMap.put("car_plate", carBland);
            flagMap.put("relacation_id", SessionUtil.getUserId(session));
            comCars = comCarChargeService.selectByMap(flagMap);
        } else {
            comCars = comCarChargeService.isCar(SessionUtil.getUserId(session), carBland);
        }

        if (comCars.size() > 0) {
            ComCarCharge comCarCharge = comCars.get(0);
            if (comCarCharge.getMoeny().compareTo(new BigDecimal(0)) == -1) {
                resultMap.put("msg", "对不起，您的余额不足");
                resultMap.put("success", 2);
                return resultMap;
            }
        } else {
            resultMap.put("msg", "对不起，该车辆未分配给您，暂无使用权");
            resultMap.put("success", 2);
            return resultMap;
        }
        resultMap.put("msg", "");
        resultMap.put("success", 1);
        return resultMap;
    }

    //启动充电
    @RequestMapping("/useCharge")
    @ResponseBody
    public Map useCharge(String param, String carPlant, String openID, HttpSession session) {
         StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        //启动结果
        //转换枪口ID
        String connId = ScanUtil.getConnId(param);
        String useReslut = starInterFce.useCharge(token, Test.LOCAL_OPERATORID + StringCreateUtil.getRandomNumString(18), connId, null);
        Map map1 = JSONObject.parseObject(useReslut, Map.class);
        String order= map1.get("StartChargeSeq")+"";
        //订单号存为缓存KEY   openid存为value 用于启动通知
        EhcacheUtil.put("chargeStat",order+ "Data", openID);
        System.err.println("启动时候缓存order"+ EhcacheUtil.get("chargeStat",order+ "Data")+"");
        //用于停止通知
        EhcacheUtil.put("stopCharge",order + "Data", openID);
        //用于推送或者手动查询启动状态时候的保存充电记录
        EhcacheUtil.put("chargeUserPhone",order + "Data", SessionUtil.getUserPhone(session));
        EhcacheUtil.put("chargeUserId", order+ "Data", SessionUtil.getUserId(session));
        //村缓存车牌  用于推送接口
        System.err.println("useCharge接口车牌：" + carPlant);
        EhcacheUtil.put("chargeCarPlant",order + "Data", carPlant);
        return map1;

    }

    //停止充电
    @RequestMapping("/stopCharge")
    @ResponseBody
    public Map stopCharge(String order, String connectorID) {
        StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        String stopReslut = starInterFce.stopCharge(token, order, connectorID);
        Map map = JSONObject.parseObject(stopReslut, Map.class);
        return map;

    }

    // 启动  调用该接口进行手动查询状态
    @RequestMapping("/getStat")
    @ResponseBody
    public Map getStat(String order, HttpSession session) throws UnsupportedEncodingException {
        StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        //启动结果
        String useReslut = starInterFce.findUseCharge(token, order);
        Map map1 = JSONObject.parseObject(useReslut, Map.class);
        //获取车牌
        String carPlant = (String) EhcacheUtil.get("chargeCarPlant", map1.get("StartChargeSeq") + "Data");
        String openId = (String) EhcacheUtil.get("chargeStat", map1.get("StartChargeSeq") + "Data");
        if (openId != null) {
            //如果启动成功后 就添加充电记录
            if (Integer.parseInt(map1.get("StartChargeSeqStat") + "") == 2) {
                // 删除缓存
                EhcacheUtil.remove("chargeUserPhone",order + "Data");
                EhcacheUtil.remove("chargeUserId",order + "Data");
                comChargeInfoServicel.weChartInsert(map1,SessionUtil.getUserId(session),SessionUtil.getUserPhone(session),carPlant);
            }
            String messge = WxpubOAuth.sendUseMessage(openId, map1.get("StartChargeSeq") + "", carPlant, map1.get("StartChargeSeqStat") + "", map1.get("StartTime") + "", null);
            EhcacheUtil.remove("chargeCarPlant", carPlant + "Data");
        }
        //如果是正在充电中了  那么就删除缓存中的openid  不重复向用户发送消息
        if (Integer.parseInt(map1.get("StartChargeSeqStat") + "") == 2) {
            EhcacheUtil.remove("chargeStat", order + "Data");
        }

        return map1;
    }

    // 停止  调用该接口进行手动查询状态
    @RequestMapping("/findStopStat")
    @ResponseBody
    public StopChargeBean findStopStat(String order, String carPlant, HttpSession session) throws UnsupportedEncodingException {
        StarInterFce starInterFce = new StarInterFce();
        String token = starInterFce.getToken();
        // 结果 转实体类
        String useReslut = starInterFce.findUseCharge(token, order);
        StopChargeBean stopChargeBean = JSONObject.parseObject(useReslut, StopChargeBean.class);
        ChargeDetails chargeDetails = stopChargeBean.getChargeDetails().get(0);
          //修改充电明细 并且减去余额
        if (Integer.parseInt(stopChargeBean.getStartChargeSeqStat()) == 4) {
           comChargeInfoServicel.weChartUpdate(stopChargeBean,carPlant);
        }
        String openId = (String) EhcacheUtil.get("stopCharge", stopChargeBean.getStartChargeSeq() + "Data");
        EhcacheUtil.remove("stopCharge", stopChargeBean.getStartChargeSeq() + "Data");
        if (openId != null) {
            String messge = WxpubOAuth.sendStopMessage(openId, stopChargeBean.getStartChargeSeq(), stopChargeBean.getStartChargeSeqStat(), chargeDetails.getDetailStartTime(), chargeDetails.getDetailEndTime(), stopChargeBean.getTotalMoney());
        }
        return stopChargeBean;
    }


}
